import axios from "axios";
import router from "../router";
import { Loading, Message } from "element-ui";
import qs from "qs";
const instance = axios.create({
  timeout: 150000,
  baseURL: process.env.VUE_APP_BASEAPI
});
// request拦截器，实现loading加载
let loadingInstance = "";
// 添加请求拦截器，在请求头中加token
instance.interceptors.request.use(
  config => {
    if (sessionStorage.getItem("accessToken")) {
      config.headers['Authorization'] = "Bearer " + sessionStorage.getItem("accessToken");
    } else if (config.url.indexOf("/v1/captcha") != -1 || config.url.indexOf("login") != -1){
      loadingInstance = Loading.service({});
      return config;
    } else {
      router.push("/login");
      Message({
        message: "token已过期,请重新登陆!",
        type: "error",
        duration: 5 * 1000
      });
    }
    loadingInstance = Loading.service({});
    return config;
  },
  error => {
    loadingInstance.close();
    Message({
      message: error.message,
      type: "error",
      duration: 5 * 1000
    });
    return Promise.reject(error);
  }
);
// response拦截器，实现loading关闭
instance.interceptors.response.use(
  data => {
    loadingInstance.close();
    return data;
  },
  error => {
    Message({
      message: error.message,
      type: "error",
      duration: 5 * 1000
    });
    loadingInstance.close();
    return Promise.reject(error);
  }
);
export default {
  get(url, param) {
    //get请求
    return new Promise(resolve => {
      instance({
        method: "get",
        url,
        params: param
      }).then(res => {
        resolve(res);
      });
    });
  },
  post(url, param) {
    //post请求
    return new Promise(resolve => {
      instance({
        method: "post",
        url,
        data: qs.stringify(param),
        headers: { "X-Requested-With": " XMLHttpRequest " }
      }).then(res => {
        resolve(res);
      });
    });
  },
  put(url, param) {
    //post请求
    return new Promise(resolve => {
      instance({
        method: "put",
        url,
        data: qs.stringify(param),
        headers: { "X-Requested-With": " XMLHttpRequest " }
      }).then(res => {
        resolve(res);
      });
    });
  }
};
